package com.wyl.auth.util;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.DataInput;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Description
 * @Author WuYiLong
 * @Date 2025/4/13 20:51
 */
public class GeoLocationAPI {

    private static final String API_URL = "http://ip-api.com/json/%s?lang=zh-CN";

    /**
     * 根据ip获取地理位置和所在地
     * @param ip
     * @return
     */
    public static GeoLocation getLocation(String ip) {
        try {
            URL url = new URL(String.format(API_URL, ip));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            if (conn.getResponseCode() != 200) return null;

            ObjectMapper mapper = new ObjectMapper();
            JsonNode root = mapper.readTree(conn.getInputStream());

            if ("success".equals(root.get("status").asText())) {
                String city = root.get("city").asText();
                String regionName = root.get("regionName").asText();
                String country = root.get("country").asText();
                String lat = root.get("lat").asText();
                String lon = root.get("lon").asText();
                GeoLocation geoLocation = new GeoLocation();
                geoLocation.setCity(city);
                geoLocation.setCountry(country);
                geoLocation.setLat(lat);
                geoLocation.setLon(lon);
                geoLocation.setRegion(regionName);
                return geoLocation;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static class  GeoLocation{
        private String country; // 国家
        private String region; // 中国
        private String city; // 城市

        private String lat; // 纬度
        private String lon; // 经度

        public String getCountry() {
            return country;
        }

        public void setCountry(String country) {
            this.country = country;
        }

        public String getRegion() {
            return region;
        }

        public void setRegion(String region) {
            this.region = region;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getLat() {
            return lat;
        }

        public void setLat(String lat) {
            this.lat = lat;
        }

        public String getLon() {
            return lon;
        }

        public void setLon(String lon) {
            this.lon = lon;
        }
    }

    public static void main(String[] args) {
        String ip = "112.96.226.4";
        GeoLocation geoLocation = GeoLocationAPI.getLocation(ip);
        System.out.println(JSONUtil.toJsonStr(geoLocation));
    }
}